package educationaladministrationsystem.CSM.Mapper.Service.Root;

import educationaladministrationsystem.CSM.Mapper.Service.ServiceInterface.RootInterface.RootMajor;
import educationaladministrationsystem.Class.EssayDownload;
import educationaladministrationsystem.Class.EssayUpload;
import educationaladministrationsystem.CSM.Mapper.Root.RootMajorMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Base64;
import java.util.List;

@Service
public class RootMajorService implements RootMajor {
    @Autowired
    RootMajorMapper rootMajorMapper;

    @Override
    public boolean saveEssay(EssayUpload essayUpload) throws IOException {
        String encodeBase64String = null;
        if (essayUpload.getImage() != null) {
//        获得字节数组
            byte[] imageByte = essayUpload.getImage().getBytes();
//        编码
            encodeBase64String = Base64.getEncoder().encodeToString(imageByte);
        }
        return rootMajorMapper.saveEssay(essayUpload, encodeBase64String) != 0;
    }

    @Override
    public Integer getAvailableEssayId() {
        return rootMajorMapper.getAvailableEssayId() + 1;
    }

    @Override
    public List<EssayDownload> downloadEssay(Integer page, Integer pageNumber) {
        return rootMajorMapper.downloadEssay((page - 1) * pageNumber, pageNumber);
    }

    @Override
    public void deleteEssay(Integer deleteId) {
        rootMajorMapper.deleteEssay(deleteId);
    }

    @Override
    public Integer getAllPage(int pageNumber) {
        double all = rootMajorMapper.getAllPage(pageNumber);
        return (int) Math.ceil(all / pageNumber);
    }

    public EssayDownload getOneDownloadEssay(Integer id) {
        return rootMajorMapper.getOneDownloadEssay(id);
    }

    @Override
    public void updateEssay(EssayUpload essayUpload) throws IOException {
        String encodeBase64String = null;
        if (essayUpload.getImage() != null) {
//        获得字节数组
            byte[] imageByte = essayUpload.getImage().getBytes();
//        编码
            encodeBase64String = Base64.getEncoder().encodeToString(imageByte);
        }
        rootMajorMapper.updateEssay(essayUpload.getId(), essayUpload.getTitle(), encodeBase64String, essayUpload.getTextInformation());
    }
}
